from photo.models import Album, Photo
from gdata.photos.service import PhotosService
from datetime import datetime

def picasa_sync(user):    
    gd_client = PhotosService()
    
    feed_url = '/data/feed/api/user/%s' % user
    feed_url += '?kind=album'
    
    feed = gd_client.GetFeed(feed_url)
    
    albums_created = 0
    photos_created = 0
    
    for entry in feed.entry:
        a = Album.all().filter('albumid = ', entry.gphoto_id.text).get()
        if not a:
            published = datetime.strptime(entry.published.text[:-5],
                                          '%Y-%m-%dT%H:%M:%S')
            
            a = Album(slug=entry.name.text,
                      title=entry.title.text,
                      published=published,
                      link=entry.link[1].href,
                      albumid=entry.gphoto_id.text,
                      summary=entry.summary.text)
            
            if entry.media.thumbnail[0]:
                a.thumbnail = entry.media.thumbnail[0].url                
            
            a.put()
            
            albums_created += 1
            
    
    for album in Album.all():
        feed_url = '/data/feed/api/user/%s/album/%s' % (user, str(album.slug))         
        
        feed = gd_client.GetFeed(feed_url)
        
        for entry in feed.entry:
            p = Photo.all().filter('photoid = ', entry.gphoto_id.text).get()
            if not p:
                published = datetime.strptime(entry.published.text[:-5],
                                              '%Y-%m-%dT%H:%M:%S')                
                
                content = entry.media.content[0]
                p = Photo(slug=entry.gphoto_id.text,
                          title=entry.title.text,
                          published=published,
                          link=content.url,
                          width=int(content.width),
                          height=int(content.height),
                          photoid=entry.gphoto_id.text,
                          summary=entry.summary.text,
                          album=album)
                
                if entry.media.thumbnail[0]:
                    p.thumbnail = entry.media.thumbnail[0].url                
                
                p.put()
                
                photos_created +=1
                
    return albums_created, photos_created